# coding=utf8
# -*-coding:utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponseRedirect
from MainManager.models import SESSION_LOGIN_USER, SESSION_LOGIN_USER_NAME, SESSION_LOGIN_USER_ROLE
from MainManager.models import SysMenu
from RoleManager.models import SysRoleGroup
from AccountManager.models import SysAccount
from AutoOperation.util import json_util, request_util
from django.shortcuts import render


# Create your views here.
def to_login(request):
    return render(request, 'login.html', {})


def to_index(request):
    if request.session.get(SESSION_LOGIN_USER) is None:
        return render(request, 'login.html', {})
    menu_list = SysMenu.objects.all()
    return render(request, 'index.html', {'menus': menu_list})


def do_login(request):
    request.encoding = 'utf-8'
    username = request.POST.get('username')
    password = request.POST.get('password')
    account_list = SysAccount.objects.filter(account_no__exact=username, account_password__exact=password)
    if account_list.__len__() > 0:
        json_account = json_util.obj_to_dicts(account_list[0])
        role = SysRoleGroup.objects.get(id=json_account.get('account_role_id'))
        request.session[SESSION_LOGIN_USER] = json_account.__str__()
        request.session[SESSION_LOGIN_USER_NAME] = json_account.get('account_name')
        request.session[SESSION_LOGIN_USER_ROLE] = role.role_name
        return request_util.return_message('success', 1)
    else:
        return request_util.return_message('error', -1)


def logout(request):
    if request.session.get(SESSION_LOGIN_USER) is not None:
        del request.session[SESSION_LOGIN_USER]
    return HttpResponseRedirect('index.html')


def to_account(request):
    return render(request, 'account/list.html', {})


def to_welcome(request):
    return render(request, 'welcome.html', {})


def handler404(request):
    return render(request, '404.html', {})


def handler500(request):
    return render(request, '500.html', {})